package net.sf.midollo.net.server;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

import net.sf.midollo.utils.MidpUtils;
import net.sf.midollo.utils.Utils;

public class InetServer implements Runnable {

  protected final StreamConnectionNotifier scn;
  protected final AcceptHandler acceptHandler;
  protected Exception error;

  public InetServer(int localPort, AcceptHandler acceptHandler) throws IOException {
    this("socket://:" + localPort, acceptHandler);
  }

  public InetServer(String connName, AcceptHandler acceptHandler) throws IOException {
    Utils.log("open server");
    this.scn = (StreamConnectionNotifier)Connector.open(connName);
    if (this.scn instanceof ServerSocketConnection) {
      ServerSocketConnection scc = (ServerSocketConnection)this.scn;
      Utils.log(MidpUtils.getServerSocketConnectionId(scc) + " " + System.getProperty("microedition.hostname"));
    }
    this.acceptHandler = acceptHandler;
  }

  public Exception getError() {
    return this.error;
  }

  public void close() throws IOException {
    this.scn.close();
  }

  public void runServer() throws IOException {
    StreamConnection sc;
    try {
      while (true) {
        Utils.log("wait for client");
        sc = this.scn.acceptAndOpen();
        Utils.log("accepting client");
        this.acceptHandler.accept(sc);
      }
    } finally {
      this.acceptHandler.release();
    }
  }

  public void run() {
    try {
      runServer();
      this.error = null;
    } catch (Exception e) {
      this.error = e;
      Utils.log(e.toString());
    }
  }
}
